package com.android.basiclib.base;

import android.app.Activity;

import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.android.basiclib.R;
import com.android.basiclib.entity.LoadAction;
import com.android.basiclib.uitls.TUtil;

/**
 * LoadingFragment
 */
public abstract class BaseLoadingFragment<P extends BaseViewModel> extends Fragment {

    private LinearLayout mViewProgress;
    private FrameLayout mViewContent;
    private LinearLayout mViewError;
    private TextView mErrorText;
    protected P mViewModel;
    private LinearLayout mLl_title;
    protected boolean isFirstEnter = true;

    /**
     * 获取Context对象
     */
    protected Activity mActivity;
    private TextView mTv_base_title;


    /**
     * 获取layout的id，具体由子类实现
     */
    protected abstract int getLayoutResId();


    /**
     * 初始化操作
     */
    protected abstract void init();


    /**
     * 添加真正的布局
     */
    private void addRealContentView() {
        View contentView = LayoutInflater.from(mActivity).inflate(getLayoutResId(), mViewContent, true);
        initViews(contentView);

        //Loading头部的赋值
        String simpleName = getClass().getSimpleName();
        if (simpleName.length() > 8)
            simpleName = simpleName.substring(0, simpleName.length() - 8);
        mTv_base_title.setText(simpleName);
    }

    /**
     * 子类实现这个区findViewById
     */
    protected void initViews(View view) {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = getActivity();

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
            Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.base_fragment_progress, container, false);
        mLl_title = (LinearLayout) view.findViewById(R.id.ll_title);
        mTv_base_title = (TextView) view.findViewById(R.id.tv_base_title);
        mViewProgress = (LinearLayout) view.findViewById(R.id.view_progress);
        mViewContent = (FrameLayout) view.findViewById(R.id.view_content);
        mViewError = (LinearLayout) view.findViewById(R.id.view_error);
        mErrorText = (TextView) view.findViewById(R.id.erroe_text);
        mErrorText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onErrorViewClick();
            }
        });

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        /**  在此添加布局  和布局相关的init方法**/
        addRealContentView();

        mViewModel = createViewModel();
        //观察网络数据状态
        if (mViewModel != null) {
            mViewModel.mLoadActionLiveData.observe(this, stateObserver);
        }

        init();
        //观察其他的数据
        dataObserver();
    }

    protected abstract void dataObserver();

    /**
     * 初始化ViewModel去执行它的方法获取数据
     */
    protected P createViewModel() {
        Object o = TUtil.getInstance(this, 0);
        if (o != null) {
            try {
                return ViewModelProviders.of(this, new AutoViewModelFactory(getActivity())).get((Class<P>) o);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        } else {
            return null;
        }
    }

    /**
     * 只映射了onDestroy方法 取消任务
     */
    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mViewModel != null)
            mViewModel.cleanTask();

    }


    /* =========================== BaseView的三个回调 =====================================**/

    protected Observer stateObserver = new Observer<LoadAction>() {
        @Override
        public void onChanged(@Nullable LoadAction loadAction) {
            if (loadAction != null) {
                if (LoadAction.STATE_NORMAL == (loadAction.action)) {
                    showStateNormal();
                } else if (LoadAction.STATE_ERROR == (loadAction.action)) {
                    showStateError(loadAction.message);
                } else if (LoadAction.STATE_SUCCESS == (loadAction.action)) {
                    showStateSuccess();
                } else if (LoadAction.STATE_LOADING == (loadAction.action)) {
                    showStateLoading(loadAction.message);
                } else if (LoadAction.STATE_NO_DATA == (loadAction.action)) {
                    showStateNoData();
                }
            }
        }
    };

    protected void showStateNormal() {
    }

    protected void showStateLoading(String message) {
        if (isFirstEnter) {
            showProgressView();
        }
    }

    protected void showStateError(String message) {
        if (isFirstEnter) {
            showErrorView(message);
            isFirstEnter = false;
        }
    }

    protected void showStateSuccess() {
        if (isFirstEnter) {
            showContentView();
            isFirstEnter = false;
        }

    }

    protected void showStateNoData() {
        if (isFirstEnter) {
            showErrorView("No Data");
            isFirstEnter = false;
        }
    }


    /**
     * 由子类去实现。空界面的点击事件
     */
    public void onErrorViewClick() {
        init();
    }

    /**
     * 展示进度布局
     */
    public void showProgressView() {
        mViewProgress.setVisibility(View.VISIBLE);
        mViewContent.setVisibility(View.GONE);
        mViewError.setVisibility(View.GONE);
        mLl_title.setVisibility(View.GONE);
    }

    /**
     * 展示内容布局
     */
    public void showContentView() {
        mViewProgress.setVisibility(View.GONE);
        mViewContent.setVisibility(View.VISIBLE);
        mViewError.setVisibility(View.GONE);
        mLl_title.setVisibility(View.GONE);
    }

    /**
     * 展示空布局
     */
    public void showErrorView(String msg) {
        mErrorText.setText(msg);
        mViewProgress.setVisibility(View.GONE);
        mViewContent.setVisibility(View.GONE);
        mViewError.setVisibility(View.VISIBLE);
        mLl_title.setVisibility(View.GONE);
    }


}
